import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Category } from './category.entity';

@Injectable()
export class CategoryService {

    constructor(
        @InjectRepository(Category)
        private readonly categoryRepository: Repository<Category>,
    ){}
    
    public async get(id: number): Promise<Category>{
        const data = await this.categoryRepository.findOne(id)
        if(!data){
            throw new HttpException("ID错误", HttpStatus.BAD_REQUEST)
        }
        return data
    }

    public async list(): Promise<Category[]>{
        const list = await this.categoryRepository.find()
        return list
    }

    public async edit(
        id: number,
        category: Category,
    ): Promise<Category>{
        const data = await this.get(id)
        await this.categoryRepository.update({
            id,
        },{
            name: category.name
        })
        data.name = category.name
        return data
    }

    public async add(category: Category): Promise<Category>{
        const data = await this.categoryRepository.save({
            name: category.name
        })
        return data
    }

    public async del(id: number){
        await this.categoryRepository.delete(id)
    }

}
